package freedom.utils.enumplus;

import java.util.Objects;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * <p>
 * 枚举扩展接口，可以持久化value，通过value反序列化，序列化value、display。<br>
 * 枚举构造器的入参value支持字符串及可以和字符串互转的基本类型，如：intger。 <br>
 * value最终以字符串持久化，domian引用该枚举时，需自定义数据类型，如：
 * 
 * <pre>
 * &#64;Entity
 * &#64;org.hibernate.annotations.Table(appliesTo = "article", comment = "文章")
 * public class Article extends BaseDomain {
 * 
 *    &#064;Column(nullable = false, columnDefinition = "varchar(1) comment '状态'")
 *    private ArticleStatus status;
 * 		... 
 * }
 * </pre>
 * 
 * @author charlie
 * @date 2019年7月13日下午3:11:23
 * @email tingfangcao@163.com
 */
@JsonDeserialize(using = EnumPlusDeserializer.class)
@JsonSerialize(using = EnumPlusSerializer.class)
public interface EnumPlus {

    public static final String PROP_VALUE = "value";
    public static final String PROP_DISPLAY = "display";
    public static final String I18N_MISS_DISPLAY = "miss";
    public static final boolean IS_STRICT_I18N = false;

    /**
     * 存储到数据库的枚举值，国际化、反序列化的依据
     *
     * @return
     */
    Object getValue();

    /**
     * <p>
     * Description: 按枚举的value获取枚举实例，可用于反序列化
     * </p>
     * 
     * @param enumClass
     * @param value
     * @return
     */
    public static <EP extends EnumPlus> EP fromValue(Class<EP> enumClass, Object value) {
        if (!StringUtils.hasText(String.valueOf(value)))
            return null;
        for (EP object : enumClass.getEnumConstants()) {
            if (Objects.equals(String.valueOf(value), String.valueOf(object.getValue()))) {
                return object;
            }
        }
        throw new IllegalArgumentException("No enum value " + value + " of " + enumClass.getCanonicalName());
    }

}
